package com.nmwlw.demo.data.viewModle

import android.util.Log
import androidx.lifecycle.ViewModel
import com.nmwlw.demo.data.bean.ComBean
import com.nmwlw.demo.data.state.ComAssistantState
import com.nmwlw.demo.utlis.MyFunc
import com.nmwlw.demo.utlis.SerialHelper
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import java.io.IOException
import java.security.InvalidParameterException
import java.util.Queue
import java.util.concurrent.ConcurrentLinkedQueue

class ComAssistantModel : ViewModel() {


    val comA: SerialControl
    val comB: SerialControl
    val comC: SerialControl
    val comD: SerialControl
    val dispQueue:DispQueueThread
    // 初始化端口和接收线程
    init {
        dispQueue = DispQueueThread()
        dispQueue.start()
        comA = SerialControl()
        comB = SerialControl()
        comC = SerialControl()
        comD = SerialControl()
    }
    // viewModel生命周期结束后关闭端口和线程
    override fun onCleared() {
//        dispQueue.interrupt()
    }


    private val _comAssistantState = MutableStateFlow(ComAssistantState())
    // 只读流
    val comAssistantState:StateFlow<ComAssistantState> = _comAssistantState.asStateFlow()

    // 记录当前选择的端口
    val currentComA = arrayOf(_comAssistantState.value.comASelectedOption)
    val currentComB = arrayOf(_comAssistantState.value.comBSelectedOption)
    val currentComC = arrayOf(_comAssistantState.value.comCSelectedOption)
    val currentComD = arrayOf(_comAssistantState.value.comDSelectedOption)

    // 记录当前选择的波特率
    val currentBaudA = arrayOf(_comAssistantState.value.baudASelectedOption)
    val currentBaudB = arrayOf(_comAssistantState.value.baudBSelectedOption)
    val currentBaudC = arrayOf(_comAssistantState.value.baudCSelectedOption)
    val currentBaudD = arrayOf(_comAssistantState.value.baudDSelectedOption)

    /**
     * 下拉框选择状态改变
     */
    fun changeExpanded(com: String,type: Int) {
        if (type == 0) {
            if (com.equals("A")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comAExpanded = !(_comAssistantState.value.comAExpanded))
                }
            } else if (com.equals("B")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comBExpanded = !(_comAssistantState.value.comBExpanded))
                }
            } else if (com.equals("C")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comCExpanded = !(_comAssistantState.value.comCExpanded))
                }
            } else if (com.equals("D")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comDExpanded = !(_comAssistantState.value.comDExpanded))
                }
            }
        }else if (type == 1) {
            if (com.equals("A")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(baudAExpanded = !(_comAssistantState.value.baudAExpanded))
                }
            } else if (com.equals("B")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(baudBExpanded = !(_comAssistantState.value.baudBExpanded))
                }
            } else if (com.equals("C")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(baudCExpanded = !(_comAssistantState.value.baudCExpanded))
                }
            } else if (com.equals("D")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(baudDExpanded = !(_comAssistantState.value.baudDExpanded))
                }
            }
        }else if (type == 2) {
            if (com.equals("A")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comAChecked = !(_comAssistantState.value.comAChecked))
                }
            } else if (com.equals("B")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comBChecked = !(_comAssistantState.value.comBChecked))
                }
            } else if (com.equals("C")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comCChecked = !(_comAssistantState.value.comCChecked))
                }
            } else if (com.equals("D")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comDChecked = !(_comAssistantState.value.comDChecked))
                }
            }
        }
    }

    /**
     * 处理用户输入
     */
    fun comInputText(com: String,text: String) {
        if (com.equals("A")) {
            _comAssistantState.update {
                    currentState ->
                currentState.copy(comAText = text)
            }
        } else if (com.equals("B")) {
            _comAssistantState.update {
                    currentState ->
                currentState.copy(comBText = text)
            }
        } else if (com.equals("C")) {
            _comAssistantState.update {
                    currentState ->
                currentState.copy(comCText = text)
            }
        } else if (com.equals("D")) {
            _comAssistantState.update {
                    currentState ->
                currentState.copy(comDText = text)
            }
        }
    }

    /**
     * 处理下拉框选择操作
     */
    fun optionsSelect(com: String, select: String, type: Int) {
        if (type == 0) {
            if (com.equals("A")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comASelectedOption = select)
                }
                if (!select.equals(currentComA[0])) {
                    // 关闭串口
                    CloseComPort(comA)
                    currentComA[0] = select
                    _comAssistantState.update {
                            currentState ->
                        currentState.copy(comAChecked = false)
                    }
                }
            } else if (com.equals("B")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comBSelectedOption = select)
                }
                if (!select.equals(currentComB[0])) {
                    // 关闭串口
                    CloseComPort(comB)
                    currentComB[0] = select
                    _comAssistantState.update {
                            currentState ->
                        currentState.copy(comBChecked = false)
                    }
                }
            } else if (com.equals("C")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comCSelectedOption = select)
                }
                if (!select.equals(currentComC[0])) {
                    // 关闭串口
                    CloseComPort(comC)
                    currentComC[0] = select
                }
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comCChecked = false)
                }
            } else if (com.equals("D")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comDSelectedOption = select)
                }
                if (!select.equals(currentComD[0])) {
                    // 关闭串口
                    CloseComPort(comD)
                    currentComD[0] = select
                }
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(comDChecked = false)
                }
            }
        }else if (type == 1) {
            if (com.equals("A")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(baudASelectedOption = select)
                }
                if (!select.equals(currentBaudA[0])) {
                    // 关闭串口
                    CloseComPort(comA)
                    currentBaudA[0] = select
                    _comAssistantState.update {
                            currentState ->
                        currentState.copy(comAChecked = false)
                    }
                }
            } else if (com.equals("B")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(baudBSelectedOption = select)
                }
                if (!select.equals(currentBaudB[0])) {
                    // 关闭串口
                    CloseComPort(comB)
                    currentBaudB[0] = select
                    _comAssistantState.update {
                            currentState ->
                        currentState.copy(comBChecked = false)
                    }
                }
            } else if (com.equals("C")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(baudCSelectedOption = select)
                }
                if (!select.equals(currentBaudC[0])) {
                    // 关闭串口
                    CloseComPort(comC)
                    currentBaudC[0] = select
                    _comAssistantState.update {
                            currentState ->
                        currentState.copy(comCChecked = false)
                    }
                }
            } else if (com.equals("D")) {
                _comAssistantState.update {
                        currentState ->
                    currentState.copy(baudDSelectedOption = select)
                }
                if (!select.equals(currentBaudD[0])) {
                    // 关闭串口
                    CloseComPort(comD)
                    currentBaudD[0] = select
                    _comAssistantState.update {
                            currentState ->
                        currentState.copy(comDChecked = false)
                    }
                }
            }
        }
    }

    /**
     * 清除控制台
     */
    fun cleanContext() {
        _comAssistantState.update {
            currentState ->
            currentState.copy(currentContext = "")
        }
    }

    /**
     * 文本模式和16进制模式切换
     */
    fun changeContextType() {
        _comAssistantState.update {
            currentState ->
            currentState.copy(enableHex = !(comAssistantState.value.enableHex))
        }
    }
    /**
     * 串口开关
     */
    fun comOpen(com: String) {
        val comAC = comAssistantState.value.comAChecked
        val comBC = comAssistantState.value.comBChecked
        val comCC = comAssistantState.value.comCChecked
        val comDC = comAssistantState.value.comDChecked

        if (com.equals("A")) {
            if (comAC) {
                comA.setBaudRate(comAssistantState.value.baudASelectedOption)
                comA.setPort(comAssistantState.value.comASelectedOption)
                OpenComPort(comA)
            }
        } else if (com.equals("B")) {
            if (comBC) {
                comB.setBaudRate(comAssistantState.value.baudASelectedOption)
                comB.setPort(comAssistantState.value.comASelectedOption)
                OpenComPort(comB)
            }
        } else if (com.equals("C")) {
            if (comCC) {
                comC.setBaudRate(comAssistantState.value.baudASelectedOption)
                comC.setPort(comAssistantState.value.comASelectedOption)
                OpenComPort(comC)
            }
        } else if (com.equals("D")) {
            if (comDC) {
                comD.setBaudRate(comAssistantState.value.baudASelectedOption)
                comD.setPort(comAssistantState.value.comASelectedOption)
                OpenComPort(comD)
            }
        }
    }

    /**
     * 发送信息
     */
    fun btnSend(com: String) {
        if (com.equals("A")) {
            sendPortData(comA,comAssistantState.value.comAText)
        } else if (com.equals("B")) {
            sendPortData(comB,comAssistantState.value.comBText)
        } else if (com.equals("C")) {
            sendPortData(comC,comAssistantState.value.comCText)
        } else if (com.equals("D")) {
            sendPortData(comD,comAssistantState.value.comDText)
        }
    }

    /**
     * 处理接收的数据
     */
    fun  DispRecData(comData: ComBean) {
        val sMsg = StringBuilder()
        sMsg.append(comData.sRecTime)
        sMsg.append("[")
        sMsg.append(comData.sComPort)
        sMsg.append("]")
        if (comAssistantState.value.enableHex) {
            sMsg.append("[Hex] ")
            sMsg.append(MyFunc.ByteArrToHex(comData.bRec))

        }else {
            sMsg.append("[Txt] ")
            sMsg.append(String(comData.bRec))
        }
        sMsg.append("\r\n")
        _comAssistantState.update {
                currentState ->
            currentState.copy(currentContext = comAssistantState.value.currentContext + sMsg.toString())
        }
    }
    /**
     * 屏幕接收串口数据处理
     */
    inner class SerialControl(): SerialHelper() {
        // 这里是一条线程，调用开启端口open方法后线程start
        override fun onDataReceived(ComRecData: ComBean) {
            dispQueue.addQueue(ComRecData)
        }
    }

    inner class DispQueueThread : Thread() {
        private val queueList: Queue<ComBean> = ConcurrentLinkedQueue()

        override fun run() {
            while (!isInterrupted) {
                val comData = queueList.poll()
                if (comData != null) {
                    DispRecData(comData)
                } else {
                    try {
                        sleep(50)
                    } catch (e: InterruptedException) {
                        break
                    }
                }
            }
        }

        @Synchronized
        fun addQueue(comData: ComBean?) {
            comData?.let { queueList.add(it) }
        }
    }


    /**
     * 开启串口
     */
    private fun OpenComPort(ComPort: SerialHelper){
        try {
            ComPort.open()
        } catch (e: SecurityException) {
            Log.d("ERROR!!!","打开串口失败:没有串口读/写权限!")
        } catch (e: IOException) {
            Log.d("ERROR!!!","打开串口失败:未知错误!")
        } catch (e: InvalidParameterException) {
            Log.d("ERROR!!!","打开串口失败:参数错误!")
        }
    }

    /**
     * 关闭串口
     */
    fun CloseComPort(ComPort: SerialHelper?) {
        if (ComPort != null) {
            ComPort.stopSend()
            ComPort.close()
        }
    }
    /**
     * 串口发送
     */
    private fun sendPortData(ComPort: SerialHelper?, sOut: String) {
        if (comAssistantState.value.enableHex) {
            if (ComPort != null && ComPort.isOpen) {
                ComPort.sendHex(sOut)
            }
        }else{
            if (ComPort != null && ComPort.isOpen) {
                ComPort.sendTxt(sOut)
            }
        }
    }


}